package zcw.com.lib_leet_code;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import zcw.com.lib_leet_code.bean.TreeNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/8/9.<br><br>
 *
 * 简单：二叉搜索树中的众数
 */
public class Topic501 {

    public static void main(String[] args) {
        Topic501 instance = new Topic501();

        List<Integer> list = Arrays.asList(1, null, 2, null, null, 2);
        TreeNode root = Util.createTree(list);
        Util.printArray(instance.findMode(root));

        instance.init();
        list = Arrays.asList(0);
        root = Util.createTree(list);
        Util.printArray(instance.findMode(root));
    }

    private List<Integer> list = new ArrayList<>();
    private int base = Integer.MIN_VALUE;
    private int count = 0;
    private int maxCount = 0;

    public int[] findMode(TreeNode root) {
        inorder(root);

        int[] result = new int[list.size()];
        for(int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }

    private void inorder(TreeNode root) {
        if(root == null) {
            return ;
        }

        inorder(root.left);
        handle(root.val);
        inorder(root.right);
    }

    private void handle(int value) {
        if(value == base) {
            count++;
        }
        else {
            base = value;
            count = 1;
        }

        if(count == maxCount) {
            list.add(base);
        }

        if(count > maxCount) {
            maxCount = count;
            list.clear();
            list.add(base);
        }
    }

    private void init() {
        list.clear();
        count = 0;
        maxCount = 0;
        base = Integer.MIN_VALUE;
    }
}
